<?php
/**
 * Create by 11li
 * Date 2020/2/10
 * Time 11:25
 *
 */

namespace app\common\service;


use app\common\model\Order;
use app\common\model\Promoter;
use app\common\model\PromoterGoods;
use app\common\model\User;
use think\Db;

class PromoterService extends BaseService
{
	
	public function __construct()
	{
		$this->model = new Promoter();
	}
	
	/**
	 * 获取推广员推广商品
	 * @param $userId
	 * @return false|\PDOStatement|string|\think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function getPromoterGoods($userId)
	{
		$model = new PromoterGoods();
		return $model->getNormalGoodsByUserId($userId);
	}
	
	public function savePromoterGoods($userId, $goodsIds)
	{
		//查找原来的推广商品
		$model = new PromoterGoods();
		$ids = $model->where([
			'user_id' => $userId,
			'status' => StatusService::STATUS_NORMAL
		])->column('goods_id', 'id');
		
		//要删除的ID
		$delGoodsIds = array_diff($ids, $goodsIds);
		
		//新增的ID
		$addGoodsIds = array_diff($goodsIds, $ids);
		
		if($delGoodsIds) {
			$delRes = $model->save(['status' => StatusService::STATUS_DISABLED],
				[
				'user_id' => $userId,
				'goods_id' => ['in', $delGoodsIds]
			]);
			
			if(!$delRes) {
				$this->error = '删除推广商品出错';
				return false;
			}
		}
		
		if($addGoodsIds) {
			$addData = [];
			foreach ($addGoodsIds as $goodsId) {
				$addData[] = [
					'user_id' => $userId,
					'goods_id' => $goodsId
				];
			}
			
			$addRes = $model->isUpdate(false)->saveAll($addData);
			if(!$addRes) {
				$this->error = '添加推广商品出错';
				return false;
			}
		}
		
		return true;
		
	}
	
	public function getPromoterInfo($userId)
	{
		$model = new Promoter();
		$info = $model->getNormalPromoterByUserId($userId);
		if($info) {
		    $info['commission'] = round($info['commission'], 2);
			$info['disabled_commission'] = round($info['disabled_commission'], 2);
			return $info;
		}
		
		return false;
	}
	
	/**
	 * 开通权限
	 * @param $userId
	 * @return bool
	 */
	public function openRole($userId)
	{
		$model = new Promoter();
		$row = $model->where(['user_id' => $userId])->find();
		if($row && $row['status'] == StatusService::STATUS_DISABLED) {
			$this->error = '你的身份已禁用，请与客服联系';
			return false;
		}
		
		if(!$row) {
			
			//查看是否有支付订单
			$order = Order::get(['user_id' => $userId, 'pay_status' => StatusService::PAYMENT_STATUS_SUCCESS]);
			if(!$order) {
				$this->error = '购买商品后才可开通代理';
				return false;
			}
			
			$res = $model->isUpdate(false)
				->save([
					'user_id' => $userId
				]);
			if(!$res) {
				$this->error = '开通身份出错';
				return false;
			}
		}
		
		return true;
		
		
	}
	
	/**
	 * 根据用户获取粉丝
	 * @param $userId
	 * @param $page
	 * @return array
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function getFansByUserId($userId, $page)
	{
		$model = new User();
		$where = [
			'recommend_id' => $userId,
			'status' => 'normal'
		];
		
		$total = (new Promoter())->getPromoterFansNumber($userId);
		$list = [];
		if($total > 0) {
			$list = $model->where($where)
				->field('id, avatar, nickname, from_unixtime(jointime) as date')
				->page($page)
				->order(['jointime' => 'desc'])
				->select();
		}
		
		return [
			'total' => $total,
			'list' => $list,
			'page' => $page
		];
	}
	
	/**
	 * 获取推荐的订单
	 * @param $userId
	 * @param $page
	 * @return array
	 * @throws \think\Exception
	 */
	public function getRecommendOrderByUserId($userId, $page)
	{
		$where = [
			'recommend_user_id' => $userId,
			'pay_status' => StatusService::PAYMENT_STATUS_SUCCESS
		];
		
		$total = Db::name('order')->where($where)->count();
		$list = [];
		if($total > 0) {
			$model = new OrderService();
			$list = $model->getRecommendOrderList($userId, $page);
		}
		
		return [
			'total' => $total,
			'list' => $list,
			'page' => $page
		];
	}
	
	public function getVisitorByUserId($userId, $page)
	{
		$where = [
			'v.share_user_id' => $userId
		];
		
		$count = Db::name('visitor')->alias('v')
			->where($where)
			->count();
		
		$list = [];
		if($count > 0) {
			$list = Db::name('visitor')->alias('v')
				->join('user u', 'v.user_id = u.id', 'left')
				->where($where)
				->field('u.avatar, u.nickname, from_unixtime(v.create_time) as date')
				->order(['v.create_time' => 'desc'])
				->group('v.user_id')
				->page($page)
				->select();
		}
		
		return [
			'total' => $count,
			'list' => $list,
			'page' => $page
		];
		
	}
	
	/**
	 * 主页显示的商品列表
	 * @param $userId
	 * @param $page
	 */
	public function getPromoterGoodsList($userId, $page, $size)
	{
		$where = [
			'pg.user_id' => $userId,
			'pg.status' => StatusService::STATUS_NORMAL
		];
		
		$count = Db::name('promoterGoods')->alias('pg')
			->where($where)
			->count();
		$list = [];
		if($count > 0) {
			$list = Db::name('promoterGoods')->alias('pg')
				->join('goods g', 'pg.goods_id = g.id', 'left')
				->where($where)
				->where(['g.status' => StatusService::STATUS_NORMAL])
				->field('g.id, g.image, g.banner_images, g.price, g.goods_name, g.sale_number')
				->page($page, $size)
				->order(['pg.sort' => 'asc', 'g.sort' => 'asc'])
				->select();
			
			if($list) {
				foreach ($list as &$item) {
					$item['banner_images'] = array_filter(explode(',', $item['banner_images']));
				}
			}
		}
		
		return [
			'total' => $count,
			'list' => $list,
			'page' => $page
		];
	}
	
	public function getPromoterDetail($userId)
	{
		$model = new Promoter();
		$info = Db::name('promoter')->alias('p')
			->join('user u', 'p.user_id = u.id', 'left')
			->field('p.id, u.avatar, u.nickname, p.fans_number, p.visible_number')
			->where(['p.user_id' => $userId, 'p.status' => StatusService::STATUS_NORMAL])
			->find();
		
		if($info) {
			return $info;
		}
		
		$this->error = '推荐人不存在或已禁用';
		return false;
	}
	
	
	/**
	 * 添加统计数据
	 * @param $orderId
	 * @return bool
	 * @throws \think\exception\DbException
	 */
	public function addNumber($orderId)
	{
		$order = Order::get($orderId);
		
		if($order['recommend_user_id']) {
			$promoter = Promoter::get(['user_id' => $order['recommend_user_id']]);
			if($promoter) {
				$res = (new Promoter())
					->save([
						'order_number' => $promoter['order_number'] + 1,
						'goods_number' => $promoter['goods_number'] + $order['number'],
						'order_amount' => $promoter['order_amount'] + $order['amount']
					], ['id' => $promoter['id']]);
				
				if(!$res) {
					$this->error = '更改推荐人数量出错';
					return false;
				}
			}
		}
		
		return true;
	}
	
	/**
	 * 添加粉丝数量
	 * @param $followUserId
	 * @return bool
	 */
	public function addFansNumber($followUserId)
	{
		$res = $this->model->where(['user_id' => $followUserId])
			->setInc('fans_number');
		
		return $res === false ? false : true;
	}
	
	/**
	 * 添加访客数量
	 * @param $followUserId
	 * @return bool
	 */
	public function addVisibleNumber($followUserId)
	{
		$res = $this->model->where(['user_id' => $followUserId])
			->setInc('visible_number');
		
		return $res === false ? false : true;
	}
}